package com.neo.tiny.codegen.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neo.tiny.codegen.entity.GenConfig;
import com.neo.tiny.codegen.service.GeneratorService;
import com.neo.tiny.common.common.ResResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author yqz
 * @Description
 * @CreateDate 2022/8/4 12:29
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/gen/generator")
@Api(tags = "代码生成模块")
public class GeneratorController {

    private final GeneratorService generatorService;

    /**
     * 列表
     * @param tableName 参数集
     * @param dsName 数据源编号
     * @return 数据库表
     */
    @ApiOperation("列表")
    @GetMapping("/page")
    public ResResult<IPage<List<Map<String, Object>>>> getPage(Page page, String tableName, String dsName) {
        return ResResult.success(generatorService.getPage(page, tableName, dsName));
    }

    /**
     * 预览代码
     * @param genConfig 数据表配置
     * @return
     */
    @ApiOperation("预览代码")
    @GetMapping("/preview")
    public ResResult<Map<String, String>> previewCode(GenConfig genConfig) {
        return ResResult.success(generatorService.previewCode(genConfig));
    }

    /**
     * 生成代码
     */
    @ApiOperation("生成代码")
    @SneakyThrows
    @PostMapping("/code")
    public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
        byte[] data = generatorService.generatorCode(genConfig);
        response.reset();
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                String.format("attachment; filename=%s.zip", genConfig.getTableName()));
        response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
    }

}
